﻿// ***********************************************************************
// Assembly         : FM.校时
// Author           : NianJiTao
// Created          : 02-27-2015
//
// Last Modified By : NianJiTao
// Last Modified On : 02-27-2015
// ***********************************************************************
// <copyright file="时间修改.cs" company="">
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace FM.校时
{
    public class 时间修改
    {
        public static string 设置(DateTime 新时间)
        {
            try
            {
                设置2(新时间);
                return string.Empty;
            }
            catch (Exception ee)
            {
                return ee.Message;
            }
        }

        private static void 设置2(DateTime 新时间)
        {
            var sysTime = new SystemTime();

            sysTime.wYear = Convert.ToUInt16(新时间.Year);
            sysTime.wMonth = Convert.ToUInt16(新时间.Month);

            var n北京时间 = 新时间.Hour - 8;
            if (n北京时间 < 0)
            {
                n北京时间 += 24;
                n北京时间 %= 24;

                sysTime.wDay = Convert.ToUInt16(新时间.Day - 1);
                var w星期 = ((int)新时间.DayOfWeek - 1 + 7) % 7;
                sysTime.wDayOfWeek = Convert.ToUInt16(w星期);
            }
            else
            {
                sysTime.wDay = Convert.ToUInt16(新时间.Day);
                sysTime.wDayOfWeek = Convert.ToUInt16(新时间.DayOfWeek);
            }
            sysTime.wHour = Convert.ToUInt16(n北京时间);
            sysTime.wMinute = Convert.ToUInt16(新时间.Minute);
            sysTime.wSecond = Convert.ToUInt16(新时间.Second);
            sysTime.wMiliseconds = Convert.ToUInt16(新时间.Millisecond + 1);

            UnsafeNativeMethods.设置系统时间(ref sysTime);
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SystemTime
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMiliseconds;
    }

    public static class UnsafeNativeMethods
    {
        public static bool 设置系统时间(ref SystemTime sysTime)
        {
            return SetSystemTime(ref sysTime);
        }


        [DllImport("Kernel32.dll")]
        static extern bool SetSystemTime(ref SystemTime sysTime);
 
    }
}
